package com.frame.project.service.monitor.job.imp;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.persistence.criteria.Predicate;

import org.quartz.JobDataMap;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.frame.common.constant.ScheduleConstants;
import com.frame.common.enumutil.RemoveEnum;
import com.frame.common.exception.job.TaskException;
import com.frame.common.utils.StringUtils;
import com.frame.common.utils.text.Convert;
import com.frame.framework.utils.quartz.CronUtils;
import com.frame.framework.utils.quartz.ScheduleUtils;
import com.frame.framework.web.service.imp.AbstractBaseService;
import com.frame.project.domain.monitor.job.Job;
import com.frame.project.repository.monitor.job.JobRepository;
import com.frame.project.service.monitor.job.JobService;


/**
 * 
 * @className ：JobService
 * @describe ：定时任务调度信息
 */
@Service
public class JobServiceImpl extends AbstractBaseService<Job> implements JobService {

	@Autowired
    private Scheduler scheduler;
	
	@Autowired
	private JobRepository jobRepository;
	
   /**
     * 项目启动时，初始化定时器 
     * 主要是防止手动修改数据库导致未同步到定时任务处理（注：不能手动修改数据库ID和任务组名，否则会导致脏数据）
     */
    @PostConstruct
    public void init() throws SchedulerException, TaskException
    {
        scheduler.clear();
        List<Job> jobList = findAllByRs(RemoveEnum.NOT_REMOVE.getCode());
        for (Job job : jobList)
        {
            ScheduleUtils.createScheduleJob(scheduler, job);
        }
    }

    /**
     * 分页
     */
	@Override
	public Page<Job> findByPage(Integer pageNo, Integer pageSize, Job job) {
		List<Sort.Order> orders = new ArrayList<>();
		orders.add(new Sort.Order(Sort.Direction.DESC, "id"));
		Sort sort = Sort.by(orders);
		Pageable pageable = PageRequest.of(pageNo, pageSize, sort);
		
		Page<Job> page = jobRepository.findAll((root, query, cb) ->{
			List<Predicate> list = new ArrayList<>();
			list.add(cb.and(cb.equal(root.get("removeStatus").as(Integer.class), RemoveEnum.NOT_REMOVE.getCode())));
			
			if(StringUtils.isNotBlank(job.getJobName())) {
				list.add(cb.and(cb.like(root.get("jobName").as(String.class), job.getJobName())));
			}
			
			if(StringUtils.isNotBlank(job.getJobGroup())) {
				list.add(cb.and(cb.equal(root.get("jobGroup").as(String.class), job.getJobGroup())));
			}
			
			if(StringUtils.isNotBlank(job.getStatus())) {
				list.add(cb.and(cb.equal(root.get("status").as(String.class), job.getStatus())));
			}
			
			if(StringUtils.isNotBlank(job.getInvokeTarget())) {
				list.add(cb.and(cb.like(root.get("invokeTarget").as(String.class), job.getInvokeTarget())));
			}
			
			Predicate[] p = new Predicate[list.size()];
			return cb.and(list.toArray(p));
		},pageable);
		
		return page;
	}
	
	 /**
     * 暂停任务
     * 
     * @param job 调度信息
     */
    @Override
    @Transactional
    public void pauseJob(Job job) throws SchedulerException
    {
        Long jobId = job.getId();
        String jobGroup = job.getJobGroup();
        job.setStatus(ScheduleConstants.Status.PAUSE.getValue());
        modify(job);
        
        scheduler.pauseJob(ScheduleUtils.getJobKey(jobId, jobGroup));
    }
    
    /**
     * 恢复任务
     * 
     * @param job 调度信息
     */
    @Override
    @Transactional
    public void resumeJob(Job job) throws SchedulerException
    {
        Long jobId = job.getId();
        String jobGroup = job.getJobGroup();
        job.setStatus(ScheduleConstants.Status.NORMAL.getValue());
        modify(job);
        
        scheduler.resumeJob(ScheduleUtils.getJobKey(jobId, jobGroup));
    }
    
    /**
     * 删除任务后，所对应的trigger也将被删除
     * 
     * @param job 调度信息
     */
    @Override
    @Transactional
    public void deleteJob(Job job) throws SchedulerException
    {
        Job j = findById(job.getId());
        j.setStatus(ScheduleConstants.Status.PAUSE.getValue());
        j.setRemoveStatus(RemoveEnum.REMOVE.getCode());
        modify(j);
        
        scheduler.deleteJob(ScheduleUtils.getJobKey(j.getId(), j.getJobGroup()));
    }
    
    /**
     * 批量删除调度信息
     * 
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    @Transactional
    public void deleteJobByIds(String ids) throws SchedulerException
    {
        Long[] jobIds = Convert.toLongArray(ids);
        for (Long jobId : jobIds)
        {
            Job job = findById(jobId);
            deleteJob(job);
        }
    }
    
    /**
     * 任务调度状态修改
     * 
     * @param job 调度信息
     */
    @Override
    @Transactional
    public void changeStatus(Job job) throws SchedulerException
    {
        String status = job.getStatus();
        if (ScheduleConstants.Status.NORMAL.getValue().equals(status))
        {
            resumeJob(job);
        }
        else if (ScheduleConstants.Status.PAUSE.getValue().equals(status))
        {
            pauseJob(job);
        }
    }
    
    /**
     * 立即运行任务
     * 
     * @param job 调度信息
     */
    @Override
    @Transactional
    public void run(Job job) throws SchedulerException
    {
        Long jobId = job.getId();
        Job tmpObj = findById(job.getId());
        // 参数
        JobDataMap dataMap = new JobDataMap();
        dataMap.put(ScheduleConstants.TASK_PROPERTIES, tmpObj);
        scheduler.triggerJob(ScheduleUtils.getJobKey(jobId, tmpObj.getJobGroup()), dataMap);
    }
    
    /**
     * 新增任务
     * 
     * @param job 调度信息 调度信息
     */
    @Override
    @Transactional
    public void insertJob(Job job) throws SchedulerException, TaskException
    {
        job.setStatus(ScheduleConstants.Status.PAUSE.getValue());
        add(job);
        
        ScheduleUtils.createScheduleJob(scheduler, job);
    }
    
    /**
     * 更新任务的时间表达式
     * 
     * @param job 调度信息
     */
    @Override
    @Transactional
    public void updateJob(Job job) throws SchedulerException, TaskException
    {
        Job j = findById(job.getId());
        j.setJobName(job.getJobName());
        j.setJobGroup(job.getJobGroup());
        j.setInvokeTarget(job.getInvokeTarget());
        j.setCronExpression(job.getCronExpression());
        j.setConcurrent(job.getConcurrent());
        j.setMisfirePolicy(job.getMisfirePolicy());
        j.setStatus(job.getStatus());
        
        modify(j);
        
        updateSchedulerJob(j, j.getJobGroup());
    }
    
    /**
     * 更新任务
     * 
     * @param job 调度信息
     * @param jobGroup 任务组名
     */
    public void updateSchedulerJob(Job job, String jobGroup) throws SchedulerException, TaskException
    {
        Long jobId = job.getId();
        // 判断是否存在
        JobKey jobKey = ScheduleUtils.getJobKey(jobId, jobGroup);
        if (scheduler.checkExists(jobKey))
        {
            // 防止创建时存在数据问题 先移除，然后在执行创建操作
            scheduler.deleteJob(jobKey);
        }
        ScheduleUtils.createScheduleJob(scheduler, job);
    }
    
    /**
     * 校验cron表达式是否有效
     * 
     * @param cronExpression 表达式
     * @return 结果
     */
    @Override
    public boolean checkCronExpressionIsValid(String cronExpression)
    {
        return CronUtils.isValid(cronExpression);
    }
}
